package com.jg.visitor.common.utils;

import com.jg.visitor.GlobalConst;
import com.jg.visitor.config.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Slf4j
public class DateTimeUtil {

    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat(GlobalConst.TIME_FORMAT_BASE);
    private static final SimpleDateFormat SIMPLE_DATE_FORMAT_DAY = new SimpleDateFormat(GlobalConst.TIME_FORMAT_DAY);
    private static final SimpleDateFormat SIMPLE_DATE_FORMAT_YEAR = new SimpleDateFormat(GlobalConst.TIME_FORMAT_YEAR);

    public static String getTimeNow(){
        return SIMPLE_DATE_FORMAT.format(new Date());
    }

    public static String getTimeStrByLong(long timeLong){
        Date date = new Date(timeLong);

        return SIMPLE_DATE_FORMAT.format(date);
    }

    public static String getTimeAfterOneHour(){

        Calendar instance = Calendar.getInstance();

        instance.add(Calendar.HOUR,1);

        return SIMPLE_DATE_FORMAT.format(instance.getTime());
    }

    public static String getTimeBeforeOneHour(){

        Calendar instance = Calendar.getInstance();

        instance.add(Calendar.HOUR,-1);

        return SIMPLE_DATE_FORMAT.format(instance.getTime());
    }

    public static String getTimeNowOnlyDay(){
        return SIMPLE_DATE_FORMAT_DAY.format(new Date());
    }

    public static String getTimeNowOnlyYear(){
        return SIMPLE_DATE_FORMAT_YEAR.format(new Date());
    }

    public static Date getDateByStr(String str){
        try {
            return SIMPLE_DATE_FORMAT.parse(str);
        } catch (ParseException e) {
            log.error("时间转换错误！",e);
            throw new BaseException(-1,"时间转换错误！");
        }
    }

    public static long getLongByStr(String expireTime) {
        try{
            Date parse = SIMPLE_DATE_FORMAT.parse(expireTime);

            return parse.getTime();
        }catch (Exception e){
            throw new BaseException(-1,"时间转换错误!字符串:" + expireTime);
        }
    }
}
